<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        *{
            margin:0;
            padding: 0;
        }
        #div{
            width: 100px;
            height:100px;
            background-color: #f00;
            position: absolute;
            /* left:100px; */
        }
        button{
            position: relative;
            top:120px;
        }
    </style>
	<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
</head>
<body>
    <div id="div"></div>
    <button>点击开始</button>
    <button>点击停止</button>
    <script>
		let timer = null;
		$('button').eq(0).click( function() {
			let speed = 5;
			let num = 0;
			if (timer == null) {
				timer = setInterval( () => {
					num += speed;
					$('div').css('left', num + 'px');
					if ( num >= $(document).width() - $('div').width() || num <= 0 ) {
						speed = -speed;
					}
				}, 100);
			}
		}) 
		$('button').eq(1).click( function() {
			clearInterval(timer);
			timer = null;
		}) 
		
    </script>
</body>
</html>